package com.test.utils;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.FileNotFoundException;
import java.io.FileReader;

public class Tools {
    public static JsonObject readJsonFile(String jsonFullPath) {
        JsonParser parser = new JsonParser();
        JsonObject jsonObj = null;
        FileReader reader;
        try {
            reader = new FileReader(jsonFullPath);
            jsonObj = parser.parse(reader).getAsJsonObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return jsonObj;
    }

    public static String deepGetJsonStringVal(JsonObject jsonObj, String[] keyList, String defaultRet) {
        int length = keyList.length;
        int i = 1;
        String ret = null;
        try {
            for (String key : keyList) {
                if (i != length) {
                    jsonObj = jsonObj.getAsJsonObject(key);
                } else {
                    ret = jsonObj.get(key).getAsString();
                }
                i++;
            }
        } catch (Exception e) {
            ret = defaultRet;
        }
        return ret;
    }

    public static JsonObject deepGetJsonObjVal(JsonObject jsonObj, String[] keyList) {
        try {
            for (String key : keyList) {
                jsonObj = jsonObj.getAsJsonObject(key);
            }
        } catch (Exception e) {
            Logger.error("No value at the position: " + keyList);
        }
        return jsonObj;
    }

    public static JsonArray deepGetJsonArrayVal(JsonObject jsonObj, String[] keyList) {
        int length = keyList.length;
        int i = 1;
        JsonArray ret = null;
        try {
            for (String key : keyList) {
                if (i != length) {
                    jsonObj = jsonObj.getAsJsonObject(key);
                } else {
                    ret = jsonObj.getAsJsonArray(key);
                }
                i++;
            }
        } catch (Exception e) {
            ret = null;
        }
        return ret;
    }
}
